#include "./uart_recv_task.h"
#include "../driver/cmd_uart.h"
#include "../service/salve_conn.h"
#include "../driver/can_bus.h"

namespace task {

using namespace driver;
using namespace utils;
using namespace conn;
using namespace service;

static void dispatch(const Message &msg) {
    ConnInfo conn_info = msg.conn_info;
    if (conn_info.dest() != MY_ADDR) {
        canBus->write_ext_pkg(conn_info, msg.data_buf, msg.data_len);
        return;
    }
    if (conn_info.req == proto::REQ_ACK) {
        cmdUart->on_ack();
        return;
    }
    cmdUart->write_ack(conn_info.src(), conn_info.seq());
    salve_dispatch(msg);
}

static void parse_buf(const ByteView &bw) {
    using namespace proto;

    uint8_t ret_index = 0;
    uint8_t index = 0;
    for (; index < bw.len;) {
        SplitProtoRet ret = split_proto(bw.buf + index, bw.len - index, ret_index);
        if (ret == SplitProtoRet::FAIL) {
            return;
        }
        Message msg = Message::from_rs232(bw.buf + index, ret_index);
        dispatch(msg);
        index += ret_index;
    }
}

void UartRecvTask::run() {

    ByteView bw;
    for (;;) {
        cmdUart->poll(bw);
        parse_buf(bw);
    }
}

}


